package com.bmslz.monitor.helper;


import com.bmslz.monitor.base.util.DateUtil;
import com.bmslz.monitor.base.grpc.MonitorGrpcService;
import com.bmslz.monitor.base.vo.MapVo;
import com.bmslz.monitor.service.*;
import com.bmslz.monitor.base.vo.DashboardCardVo;
import com.bmslz.monitor.base.vo.ProjectDataQpsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

@Component
public class DashboardHelper {
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IMonitorModelService monitorModelService;
    @Autowired
    private IAlarmModelService alarmModelService;
    @Autowired
    private IProjectAlarmService projectAlarmService;
    @Autowired
    private IProjectDataService projectDataService;
    /**
     * 计算两个Long值的增长率（百分比）
     *
     * @param current  当前值
     * @param previous 之前的值
     * @return 增长率百分比，如果无法计算则返回null
     */
    public static Double calculateGrowthRate(Long current, Long previous) {
        // 处理空值
        if (current == null || previous == null) {
            return null;
        }

        // 处理除零情况
        if (previous == 0L) {
            return null; // 或者根据业务需求返回特定值
        }

        // 计算增长率：(当前值 - 之前值) / 之前值 * 100
        return ((current - previous) * 100.0) / previous;
    }

    /**
     * 计算增长率并格式化输出
     *
     * @param previous 之前的值
     * @param current  当前值
     * @return 格式化后的增长率字符串，如 "25.50%"
     */
    public static String calculateGrowthRateFormatted(Long previous, Long current) {
        Double growthRate = calculateGrowthRate(current, previous);

        if (growthRate == null) {
            return "N/A";
        }

        // 保留两位小数
        return String.format("%.2f%%", growthRate);
    }

    public List<DashboardCardVo> superCard() {
        List<DashboardCardVo> res = new ArrayList<>();
        //项目统计 当前
        Long projectTotalNow = projectService.total(null, new Date());
        //项目统计 上周之前
        Long projectTotalLastWek = projectService.total(null, DateUtil.getLastWeekLastDayDate());
        //用户统计 当前
        Long userTotalNow = userService.total(null, new Date());
        //用户统计 上周之前
        Long userTotalLastWek = userService.total(null, DateUtil.getLastWeekLastDayDate());
        //监控模型统计 当前
        Long monitorModelTotalNow = monitorModelService.total(null, new Date());
        //监控模型统计 上周之前
        Long monitorModelTotalLastWek = monitorModelService.total(null, DateUtil.getLastWeekLastDayDate());
        //告警模板统计 当前
        Long alarmModelTotalNow = alarmModelService.total(null, new Date());
        //告警模板统计 上周之前
        Long alarmModelTotalLastWek = alarmModelService.total(null, DateUtil.getLastWeekLastDayDate());
        //告警中的总数
        Long totalIng = projectAlarmService.totalIng();

        res.add(DashboardCardVo.builder()
                .des("项目数量")
                .icon("&#xe721;")
                .startVal(0)
                .duration(1000)
                .num(projectTotalNow)
                .change(calculateGrowthRateFormatted(projectTotalLastWek, projectTotalNow)).build());
        res.add(DashboardCardVo.builder()
                .des("用户数量")
                .icon("&#xe721;")
                .startVal(0)
                .duration(1000)
                .num(userTotalNow)
                .change(calculateGrowthRateFormatted(userTotalLastWek, userTotalNow)).build());
        res.add(DashboardCardVo.builder()
                .des("监控模型")
                .icon("&#xe721;")
                .startVal(0)
                .duration(1000)
                .num(monitorModelTotalNow)
                .change(calculateGrowthRateFormatted(monitorModelTotalLastWek, monitorModelTotalNow)).build());
        res.add(DashboardCardVo.builder()
                .des("告警模板")
                .icon("&#xe721;")
                .startVal(0)
                .duration(1000)
                .num(alarmModelTotalNow)
                .change(calculateGrowthRateFormatted(alarmModelTotalLastWek, alarmModelTotalNow)).build());
        res.add(DashboardCardVo.builder()
                .des("正在告警")
                .icon("&#xe721;")
                .startVal(0)
                .duration(1000)
                .num(totalIng)
                .change("noShow").build());
        return res;
    }

    public ProjectDataQpsVo superQps() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ProjectDataQpsVo res = new ProjectDataQpsVo();
        res.setX(new ArrayList<>());
        res.setY(new ArrayList<>());
        long currentTime = Instant.now().getEpochSecond();
        List<Long> secondList = LongStream.rangeClosed(1, 300)
                .map(i -> currentTime - i)
                .boxed()
                .collect(Collectors.toList());

        for (Long second : secondList) {
            String format = formatter.format(new Date(second * 1000));
            AtomicLong atomicLong = MonitorGrpcService.qpsMap.get(second);
            if (atomicLong == null) {
                //近5分钟 没有数据的默认为0
                res.getX().add(format);
                res.getY().add(0);
            } else {
                res.getX().add(format);
                res.getY().add(atomicLong);
            }
        }
        return res;
    }

    public List<MapVo> projectAlarmGroup() {
        return projectService.projectAlarmGroup();
    }
}
